package com.godyao;

import com.godyao.common.MyBeanFactoryPostProcessor;
import com.godyao.common.MyBeanPostProcessor;
import com.godyao.framework.beans.factory.support.DefaultListableBeanFactory;
import com.godyao.framework.beans.factory.xml.XmlBeanDefinitionReader;
import com.godyao.framework.context.support.ClassPathXmlApplicationContext;
import com.godyao.service.UserService;
import org.junit.Test;

public class ContextText {
    /**
     * 不使用应用上下文
     */
    @Test
    public void test_BeanFactoryPostProcessorAndBeanPostProcessor() {
        // 1.初始化BeanFactory
        DefaultListableBeanFactory defaultListableBeanFactory = new DefaultListableBeanFactory();

        // 2.读取配置文件&注册Bean
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(defaultListableBeanFactory);
        beanDefinitionReader.loadBeanDefinitions("classpath:spring.xml");

        // 3.BeanDefinition加载完成&Bean实例化之前，修改BeanDefinition属性值
        MyBeanFactoryPostProcessor myBeanFactoryPostProcessor = new MyBeanFactoryPostProcessor();
        myBeanFactoryPostProcessor.postProcessBeanFactory(defaultListableBeanFactory);

        // 4.Bean实例化之后，修改Bean属性
        MyBeanPostProcessor myBeanPostProcessor = new MyBeanPostProcessor();
        defaultListableBeanFactory.addBeanPostProcessor(myBeanPostProcessor);

        // 5.获取Bean对象调用方法
        UserService userService = defaultListableBeanFactory.getBean("userService", UserService.class);
        String user = userService.getUser(1);
        System.out.println(user);

        String company = userService.getCompany();
        String location = userService.getLocation();

        System.out.println("原公司：阿里爸爸,现公司："+company);
        System.out.println("原公司地址：杭州,现公司地址："+location);
        System.out.println("count："+userService.getCount());
    }


    /**
     * 使用应用上下文
     */
    @Test
    public void test_xml() {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("classpath:spring.xml");
        // 直接从工厂取
        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
//        UserService userService = classPathXmlApplicationContext.getBean("userService", UserService.class);
        String user = userService.getUser(1);
        System.out.println(user);

        String company = userService.getCompany();
        String location = userService.getLocation();

        System.out.println("原公司：阿里爸爸,现公司："+company);
        System.out.println("原公司地址：杭州,现公司地址："+location);
        System.out.println("count："+userService.getCount());
        classPathXmlApplicationContext.close();
    }
}
